package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	beego "github.com/beego/beego/v2/server/web"
)

type IhuYiRes struct {
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
	Smsid string `json:"smsid"`
}

// utils 工具/第三扩展目录
// 调用第三方或者自己封装写的功能
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

func IhuYI(mobile string, code int) bool {
	return true
	v := url.Values{}
	_now := strconv.FormatInt(time.Now().Unix(), 10)
	//fmt.Printf(_now)
	_account, _ := beego.AppConfig.String("ihuyiaccount")    //用户名是登录用户中心->验证码短信->产品总览->APIID
	_password, _ := beego.AppConfig.String("ihuyiapassword") //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
	_content := fmt.Sprintf("您的验证码是：%d。请不要把验证码泄露给其他人。", code)
	v.Set("account", _account)
	v.Set("password", GetMd5String(_account+_password+mobile+_content+_now))
	v.Set("mobile", mobile)
	v.Set("content", _content)
	v.Set("time", _now)
	//body := ioutil.NopCloser(strings.NewReader(v.Encode())) //把form数据编下码
	body := strings.NewReader(v.Encode()) //把form数据编下码
	client := &http.Client{}
	req, _ := http.NewRequest("POST", "http://106.ihuyi.com/webservice/sms.php?method=Submit&format=json", body)

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
	//fmt.Printf("%+v\n", req) //看下发送的结构

	resp, err := client.Do(req) //发送
	if err != nil {
		log.Print(err)
		return false
	}
	defer resp.Body.Close() //一定要关闭resp.Body
	data, _ := ioutil.ReadAll(resp.Body)
	log.Println(string(data))
	var res IhuYiRes
	json.Unmarshal(data, &res)

	if res.Code != 2 {
		return false
	}
	return true
}

func GetCode(length int) int {
	code := rand.Intn(length * 1000)

	for {
		if code < 999 {
			code = GetCode(length)
		}
		break //终止循环
	}
	return code
}
